namespace SimpleWebServices.Net
{
    using System;
    using System.IO;
    using System.Net;
    using System.Text;

    public sealed class NoContentResponse : Response
    {
        public NoContentResponse(HttpWebResponse response)
            : base(response.StatusCode, response.ResponseUri, response.Headers, response.Cookies)
        {
            string text = null;
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    text = reader.ReadToEnd();
                }
            }

            this.Text = text;
            if (!string.IsNullOrEmpty(text))
            {
                throw new HttpTestException(this, "The response unexpectedly has content.");
            }
        }

        public string Text
        {
            get;
            private set;
        }

        public static NoContentResponse New(HttpRequestDefinition definition, IHttpContent content)
        {
            NoContentResponse result = null;

            using (HttpWebResponse response = Response.Http(definition, content) as HttpWebResponse)
            {
                result = new NoContentResponse(response);
            }

            return result;
        }

        public override string ToString()
        {
            StringBuilder buffer = new StringBuilder();
            buffer.Append(base.ToString());
            buffer.Append(Environment.NewLine);
            buffer.Append(this.Text);

            return buffer.ToString();
        }
    }
}